const express=require('express');
const pool=require('../pool.js');

const router=express.Router();


// 获取首页所有地点(分页查询)
  router.get('/lists',(req,res,next)=>{
    const page_num = parseInt(req.query.page_num) || 1;
    const page_size = parseInt(req.query.page_size) || 10;
    const params = [(page_num-1)*page_size,page_size];
    var sql = "select * from location limit ?,?";

    pool.query(sql,params,(err,data)=>{
      if(err){next(err);return;}
      if (data.length) {
        // console.log("data:",data)
        let sqlTotal = "select count(*) as total from location"   //统计总数据条数命名为total
        pool.query(sqlTotal,(err,among) => {
          if(err){
            console.log(err);
          } else {
            // console.log(among);
            let total = among[0]['total'];
            res.json({
              "code":1,
              "message":"查询成功",
              "data":data,
              "paging":{
                page_num:page_num,
                page_size:page_size,
                total:total
              }
            })
          }
        })
      } else {
        res.json({
          code:0,
          message:'查询失败'
      })
    }
  })
})


// 首页地点分类显示
//这个路由不用接收参数
router.get('/lists/:loc_id',(req,res,next)=>{
  let obj = req.params;
  pool.query('select * from location where loc_id=?',[obj.loc_id],(err,data)=>{
    if(err){next(err);return;}
    if (data.length) {
      res.send({
        "code":1,
        "msg":"获取数据成功",
        "data":data
      })
    } else {
      res.send({
        "code":0,
        "msg":"获取数据失败"        
      })
    }
  })
})
//3.修改酒店资料
router.put('/edit',(req,res,next)=>{
  let obj=req.body;
  pool.query('update location set ? where lid=?',[obj,obj.lid],(err,result)=>{
    console.log(result);
    if(err){next(err);return;}
	  //结果是对象，如果对象下的affectedRows值为0说明修改失败，否则修改成功
    if(result.affectedRows===0){
      res.send({code:0,msg:'修改酒店失败'});
    }else{
      res.send({code:1,msg:'修改酒店成功'});
    }
  });
});

//导出路由器对象
module.exports = router;